<?php

declare(strict_types=1);
/**
 * 创建人 : Forpastime
 * 创建时间: 2023/4/10 14:45
 * 个人主页 : http://forpastime.com
 */
namespace App\Service;

use App\Event\SmsCheck;
use App\Event\UserRegistered;
use App\Model\User;
use App\Utils\Result;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
use Psr\EventDispatcher\EventDispatcherInterface;

class UserService implements UserServiceInterface
{
    /**
     * @Inject
     * @var User
     */
    protected $user;

    /**
     * @Inject
     * @var EventDispatcherInterface
     */
    private $eventDispacher;

    public function __construct(LoggerFactory $loggerFactory)
    {
    }

    /**
     * 获取用户信息.
     * @return \Hyperf\Database\Model\Collection
     */
    public function userInfo($where=[])
    {
        $user =  $this->user->where($where)->first();
        if($user){
            return $user->toArray();
        }else{
            return [];
        }
//        var_dump(User::query()->find(1)->role);
    }


    /**
     * 登录.
     * @param $clientType 客户端类型
     * @param $params
     * @return mixed|void
     */
    public function login($clientType, $params)
    {
        //var_dump($clientType,$params);
        if(isset($params['unionid']) && !empty($params['unionid'])){

            //先判断unionid
            $userInfo = $this->user->where('unionid',$params['unionid'])->first();
            if($userInfo){
                $userInfo = $userInfo->toArray();

                switch ($clientType){
                    case 'mp':
                        $userInfo['openid'] = $params['mp_openid'];
                        unset($params['avartar'],$params['nick_name']);
                        break;
                    case 'h5':
                        $userInfo['openid'] = $params['official_openid'];
                        break;
                    case 'app':
                        $userInfo['openid'] = $params['app_openid'];
                        break;
                    case 'pc':
                        $userInfo['openid'] = $params['openid'];
                        $params = [
                            'official_openid'=>$params['openid'],
                            'unionid'=>$params['unionid']
                        ];
                        break;
                    case 'work':
                        $userInfo['openid'] = $params['work_openid'];
                        break;
                }

                //更新到用户表  可能统一UnionID下的账户同步更新其他openid
                $this->user->where('id',$userInfo['id'])->update($params);
            }
        }else if(isset($params['openid']) && !empty($params['openid'])){

            //没有同账号unionid的判断openid
            switch ($clientType){
                case 'mp':
                    $params['mp_openid'] = $params['openid'];
                    $where = ['mp_openid','=',$params['openid']];
                    unset($params['avartar'],$params['nick_name']);
                    break;
                case 'h5':
                    $params['official_openid'] = $params['openid'];
                    $where = ['official_openid','=',$params['openid']];
                    break;
                case 'app':
                    $params['app_openid'] = $params['openid'];
                    $where = ['app_openid','=',$params['openid']];
                    break;
                case 'pc':
                    $where = ['official_openid','=',$params['openid']];
                    $params = [
                        'official_openid'=>$params['openid'],
                        'unionid'=>$params['unionid']
                    ];
                    break;
                case 'work':
                    $params['work_openid'] = $params['openid'];
                    $where = ['work_openid','=',$params['openid']];
                    break;
            }
            $userInfo = $this->user->where($where)->first();
            if($userInfo){
                $userInfo = $userInfo->toArray();
                //更新到用户表  可能统一UnionID下的账户同步更新其他openid

                $this->user->where('id',$userInfo['id'])->update($params);
            }
            $userInfo['openid'] = $params['openid'];
        }
        if(empty($userInfo) || !$userInfo){

            //注册
            $params['create_time'] = time();
            $userInfo = &$params;
            switch ($clientType){
                case 'mp':
                    $userInfo['openid'] = $params['mp_openid'];
                    break;
                case 'h5':
                    $userInfo['openid'] = $params['official_openid'];
                    break;
                case 'app':
                    $userInfo['openid'] = $params['app_openid'];
                    break;
                case 'pc':
                    unset($userInfo);
                    $params = [
                        'official_openid'=>$params['openid'],
                        'unionid'=>$params['unionid'],
                        'nick_name'=>substr($params['openid'],-6,6)
                    ];
                    $userInfo = $params;
                    $userInfo['openid'] = $params['official_openid'];

                    break;
                case 'work':
                    $userInfo['openid'] = $params['work_openid'];
                    break;
            }
            $userId = User::insertGetId($params);

            //var_dump('userService==',$userInfo);
            $userInfo['id'] = $userId;
        }
        return Result::data_success($userInfo);
    }

    /**
     * 注册.
     * @param $params
     * @return array|bool
     */
    public function register($params)
    {
        // 注册前短信验证
        if (! isset($params['mobile']) || ! isset($params['code'])) {
            return false;
        }
        $smsCheck = new SmsCheck($params['mobile'], $params['code'], 'regist');

        $this->eventDispacher->dispatch($smsCheck); // 调度事件

        if (! $smsCheck->isPass) {
            echo 'check wrong！' . $smsCheck->isPass;
            return Result::data_error('短信验证失败');
        }
        echo 'check right！' . $smsCheck->isPass;

        // 完成账号注册的逻辑
        $userId = User::insertGetId([
            'mobile' => $params['mobile'],
            'nick_name' => $params['name'],
            'create_time' => time(),
        ]);

        // 这里 dispatch(object $event) 事件调度器调取注册后的事件， 监听该事件的监听器会逐个运行

        $this->eventDispacher->dispatch(new UserRegistered($userId, $params['mobile']));

        return Result::data_success(['user_id' => $userId]);
    }

    public function editInfo($params)
    {
    }

    public function editPwd($params)
    {
    }

    public function changeMobile($params)
    {
    }

    /**
     * 获取用户发布的文章.
     * @return \Hyperf\Database\Model\Collection
     */
    public function userArticles()
    {
        return $this->user->article()->get();
    }

    /**
     * 获取用户列表.
     * @return mixed|void
     */
    public function getUsers($where,$orWhere,$field,$limit=10)
    {
        $res= $this->user->getList($where,$field,$limit,$orWhere);
        return $res;
    }
}
